﻿Imports OpenDelib.ServiceDeliberations

'Classe design pattern singleton pour conserver des informations liées au webservice
Public Class Tools

    Public Const DateNull As Date = #12:00:00 AM#

    Public Enum ModeFiche
        Creation = 0
        Modification = 1
    End Enum
    Private Class KeyParameter
        Public Property TypeParam As TypeParametre
        Public Property TypeDelibObl As Boolean
        Public Property TypeDelib As TypeDeliberation
    End Class

    Private Property Token As String
        Get
            Return CStr(HttpContext.Current.Session("TokenConnexion"))
        End Get
        Set(value As String)
            HttpContext.Current.Session("TokenConnexion") = value
        End Set
    End Property
    Private ReadOnly Property Parametres As Dictionary(Of KeyParameter, String)
        Get
            If HttpContext.Current.Session("Parametres") Is Nothing Then HttpContext.Current.Session("Parametres") = New Dictionary(Of KeyParameter, String)
            Return CType(HttpContext.Current.Session("Parametres"), Dictionary(Of KeyParameter, String))
        End Get
    End Property
    Public ReadOnly Property Parametre(typeParam As TypeParametre, Optional typeDelib As TypeDeliberation = CType(-1, TypeDeliberation)) As String
        Get
            For Each param As KeyValuePair(Of KeyParameter, String) In Me.Parametres
                If param.Key.TypeParam = typeParam AndAlso
                  (Not param.Key.TypeDelibObl OrElse param.Key.TypeDelib = typeDelib) Then
                    Return param.Value
                End If
            Next

            Dim value As String = ReadParameter(typeDelib, typeParam)
            Me.Parametres.Add(New KeyParameter() With {.TypeDelib = typeDelib, .TypeDelibObl = typeDelib <> -1, .TypeParam = typeParam}, value)

            Return value
        End Get
    End Property

    Private Shared instance As Tools = Nothing

    'Aucun constructeur
    Private Sub New()
    End Sub

    ' La méthode GetInstance doit être Shared
    Public Shared Function GetInstance() As Tools

        If instance Is Nothing Then
            instance = New Tools
        End If

        ' On retourne l'instance de MonSingleton
        Return instance

    End Function

    Public Function getToken() As String
        Return Token
    End Function

    Public Function isConnected() As Boolean
        Using wsConnect As New ServiceConnexion.ConnexionClient()
            Dim wsAutentificationParameters As New ServiceConnexion.AuthenticationParameters
            wsAutentificationParameters.Token = Token

            Dim paramConnect As New ServiceConnexion.OperationParameters
            paramConnect.Authentication = wsAutentificationParameters

            Dim result As ServiceConnexion.OperationResult = wsConnect.ValidateToken(paramConnect)
            Return result.OK
        End Using

        Return False
    End Function

    Public Sub deleteToken()
        HttpContext.Current.Session.Remove("TokenConnexion")
    End Sub

    Private Function ReadParameter(typeDelib As TypeDeliberation, typeParam As TypeParametre) As String
        Using svc As New DeliberationsClient
            Dim params As New ParametresLectureParam
            params.TypeDelib = If(typeDelib = -1, TypeDeliberation.Assemblee, typeDelib)
            params.TypeParam = typeParam

            Dim result As StringOperationResult

            Try
                result = svc.LireParametre(params)
            Catch ex As Exception
                Throw New Exception("Erreur pendant la récupération du paramètre." & ControlChars.NewLine & "Type de délibération : " & typeDelib.ToString & ControlChars.NewLine & "Paramètre : " & typeDelib.ToString & ControlChars.NewLine & "Erreur : " & ex.Message, ex)
            End Try

            If Not result.OK Then Throw New Exception("Erreur pendant la récupération du paramètre." & ControlChars.NewLine & "Type de délibération : " & typeDelib.ToString & ControlChars.NewLine & "Paramètre : " & typeDelib.ToString & ControlChars.NewLine & "Erreur : " & result.ErrorMessage)

            Return result.Value
        End Using
    End Function

    'Utilisé pour cacher l'url
    Public Shared Function Encrypt(text As String) As String
        Dim textBytes As Byte() = System.Text.Encoding.Unicode.GetBytes(text)
        Dim encryptedText As String = System.Convert.ToBase64String(textBytes)
        Return encryptedText
    End Function

    Public Shared Function Decrypt(encryptedText As String) As String
        Dim textByteData As Byte() = System.Convert.FromBase64String(encryptedText)
        Dim originalText As String = System.Text.Encoding.Unicode.GetString(textByteData)
        Return originalText
    End Function

    Public Shared Function LoadParametersCombo(cb As DropDownList, libellePluriel As String, entiteParametrage As Integer,
                                               Optional param1 As Object = Nothing, Optional param2 As Object = Nothing,
                                               Optional firstItem As ListItem = Nothing, Optional clearCombo As Boolean = True,
                                               Optional svc As ServiceParametre.ParametresClient = Nothing) As String
        Dim params As New ServiceParametre.ListeParametreParameters
        params.Authentication = New ServiceParametre.AuthenticationParameters
        params.Authentication.Token = Tools.GetInstance.getToken
        params.EntiteParametrage = entiteParametrage
        params.Param1 = param1
        params.Param2 = param2

        Dim close As Boolean = False
        If svc Is Nothing Then
            svc = New ServiceParametre.ParametresClient
            close = True
        End If

        Dim msg As String = ""

        Try
            Dim results As ServiceParametre.OIItemListResult = svc.ListeParametre(params)
            If results Is Nothing OrElse Not results.OK Then
                msg = "Impossible de charger les " & libellePluriel & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage)
            Else
                LoadParametersCombo(results.Liste, cb, firstItem, clearCombo)
            End If
        Catch ex As Exception
            msg = ex.Message
        End Try

        If close Then
            svc.Close()
            svc = Nothing
        End If

        Return msg
    End Function
    Public Shared Sub LoadParametersCombo(items As List(Of ServiceParametre.OIItem), cb As DropDownList, Optional firstItem As ListItem = Nothing, Optional clearCombo As Boolean = True)
        If clearCombo Then cb.Items.Clear()
        If firstItem IsNot Nothing Then cb.Items.Add(firstItem)
        For Each item As ServiceParametre.OIItem In items
            cb.Items.Add(New ListItem(item.Libelle, item.Code))
        Next
        cb.SelectedIndex = 0
    End Sub

    Public Shared Function Convert(origine As ServiceDossiers.Dossier) As ServiceAssistant.Dossier
        Dim destination As New ServiceAssistant.Dossier

        destination.ApplicationExterne = origine.ApplicationExterne
        destination.CleExterne = origine.CleExterne
        destination.Code = origine.Code
        destination.DebutValidite = origine.DebutValidite
        destination.DossierClos = origine.DossierClos
        destination.Etat = origine.Etat
        destination.FinValidite = origine.FinValidite
        destination.Identificateur = origine.Identificateur
        destination.Remarques = origine.Remarques
        destination.SuiviPar = origine.SuiviPar
        destination.Type = origine.Type

        destination.ZoneSup = New ServiceAssistant.ZoneSup
        destination.ZoneSup.Code = origine.ZoneSup.Code
        destination.ZoneSup.Date1 = origine.ZoneSup.Date1
        destination.ZoneSup.Date2 = origine.ZoneSup.Date2
        destination.ZoneSup.Numerique1 = origine.ZoneSup.Numerique1
        destination.ZoneSup.Numerique2 = origine.ZoneSup.Numerique2
        destination.ZoneSup.Numerique3 = origine.ZoneSup.Numerique3
        destination.ZoneSup.Texte1 = origine.ZoneSup.Texte1
        destination.ZoneSup.Texte2 = origine.ZoneSup.Texte2
        destination.ZoneSup.Texte3 = origine.ZoneSup.Texte3

        Return destination
    End Function

    Public Shared Function RegisterStartupScript(control As Control, ParamArray jsFunctions() As String) As Boolean
        Dim SB As System.Text.StringBuilder

        ' Si on n'a aucune fonction javascript à enregistrer, on sort
        If jsFunctions.Length = 0 Then Return False

        ' On génère le script
        SB = New System.Text.StringBuilder
        SB.AppendLine("function pageLoadedHandler_" & control.ClientID & "(sender, args) {")
        SB.AppendLine("    $(function () {")
        For Each f As String In jsFunctions
            SB.AppendLine("        " & f)
        Next
        SB.AppendLine("    });")
        SB.AppendLine("}")
        SB.AppendLine("pageLoadedHandler_" & control.ClientID & "(null, null);")

        ' Et on enregistre ce script sur la page
        control.Page.ClientScript.RegisterClientScriptBlock(control.GetType(), "Odyssee.WebControles.PageLoadedHandler." & control.UniqueID, SB.ToString, True)

        ' On génère en plus le script d'attachement de l'évènement (à éxécuter au chargement de la page)
        SB.Clear()
        SB.AppendLine("try {")
        SB.AppendLine("    window.Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler_" & control.ClientID & ");")
        SB.AppendLine("} catch(e) {")
        SB.AppendLine("}")

        ' Et on enregistre ce script sur la page au startup
        control.Page.ClientScript.RegisterStartupScript(control.GetType(), "Odyssee.WebControles.PageLoadedAddHandler." & control.UniqueID, SB.ToString & ControlChars.NewLine, True)

        Return True
    End Function

    Public Shared Sub NotifyErreur(page As Page, erreur As String)
        ScriptManager.RegisterStartupScript(page, page.GetType, "notify", "var n = noty({timeout:3000,layout:'topCenter',type:'error',text :'" & HttpUtility.JavaScriptStringEncode(erreur) & "'});", True)
    End Sub

    Public Shared Sub NotifySuccess(page As Page, msg As String)
        ScriptManager.RegisterStartupScript(page, page.GetType, "notify", "var n = noty({timeout:3000,layout:'topCenter',type:'success',text :'" & HttpUtility.JavaScriptStringEncode(msg) & "'});", True)
    End Sub

    Public Shared Sub NotifyMsg(page As Page, msg As String)
        ScriptManager.RegisterStartupScript(page, page.GetType, "notify", "var n = noty({timeout:3000,layout:'topCenter',type:'Information',text :'" & HttpUtility.JavaScriptStringEncode(msg) & "'});", True)
    End Sub

    Public Shared Function GetRowDataItem(Of TItem, TList As IList)(gv As Odyssee.WebControles.AcroGridView, row As GridViewRow) As TItem
        If gv.SessionDataSource Is Nothing Then Return Nothing
        If row Is Nothing Then Return Nothing
        If row.DataItemIndex < 0 Or row.DataItemIndex >= CType(gv.SessionDataSource, TList).Count Then Return Nothing
        Return CType(CType(gv.SessionDataSource, TList)(row.DataItemIndex), TItem)
    End Function

    Public Shared Function FormaterNumeroTelephone(numero As String) As String
        If numero.Trim.Replace(" ", "").Length <> 10 Then Return numero
        numero = numero.Trim.Replace(" ", "")
        Return numero.Substring(0, 2) & " " & numero.Substring(2, 2) & " " & numero.Substring(4, 2) & " " & numero.Substring(6, 2) & " " & numero.Substring(8, 2)
    End Function

End Class
